
/**
 * 单次多选图片上传
 */

// 选择图片
var fileArr = []; // 图片files

var file = $('#select1');
file.change(function () {
    fileArr = [];
    if (file[0].files.length) {
        Array.prototype.push.apply(fileArr, file[0].files);
    }
    for (var i = 0; i < fileArr.length; i++) {
        (function (index) {
            photoData(fileArr[index], '', '', function (result) {
                var dom = `<div class="img-box">
                                <img src="${result}" class="img-show">
                                <div class="img-remove" data-name="${fileArr[index].name}"></div>
                            </div>`;

                $('.container').append(dom);
            })
        }(i))
    }
})

// 缩略图删除
$('.container').on('click', '.img-remove', function () {
    var name = $(this).attr("data-name");
    fileArr = fileArr.filter(function (file) {
        return file.name !== name;
    });
    $('.img-box').each(function (index, ele) {
        // $(this) 指向 img-box
        if ($(this).children(".img-remove").attr("data-name") === name) {
            $(this).remove();
        }
    })
})

// 提交
function submit() {
    var form = new FormData();
    fileArr.map(function (ele, index) {
        form.append('file[]', ele)
        // form.set('file[]', ele)
    });
    console.log(form);
    console.log(form.get("file[]"));
}

/**
 * 多次单选图片上传
 */
var formData = new FormData(); // FormData 对象
var upBtn = document.getElementsByClassName('y-up-btn')
var yImg = document.getElementsByClassName('y-img')

for (var i = 0; i < upBtn.length; i++) {
    upBtn[i].onchange = (function (n) {
        //闭包
        return function () {//不压缩
            var that = this;
            photoData(this.files[0], '', '', function (result) {
                $(that).next().attr('src', result);
                formData.set(('Media' + (n + 1)), that.files[0])
            })
        }
    }(i))
}

// 提交
function submit2() {
    console.log(formData);
    console.log(formData.get("Media1"));
}
